using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Xsl;
using APJ.Util;

namespace MTRC.ODMS.Web.SOM.CodeSetup
{
    public partial class CQAQualificationMasterUpload : BasePage_SOM
    {
        /// <summary>
        /// author:Nearly 
        /// Modify by zengshunbo 2008-12-11 actionlog(0709)
        /// </summary>
        #region MenuID

        protected override string MenuID
        {
            get
            {
                return "M140821";
            }
        }

        #endregion

        #region Page Init And Load and set the page lanuage

        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.ChangeLanguage += new MTRC.ODMS.Web.BasePage.ChangeLanguageEventHandler(this.ChangeLanguage_Click);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetLanguage();
            }
        }

        private void SetLanguage()
        {
            this.lblTitle.Text = this.GetLabel("SOM_CQAQualificationMasterUpload");
            this.lblFileToBeUploaded.Text = this.GetLabel("SOM_FileToBeUploaded",true);
            this.btnUpload.Text = this.GetLabel("SOM_Upload");
            this.btnDownTemplte.Text = this.GetLabel("SOM_DownloadEmptyTemplate");
            this.lblUploadNote.Text = this.GetLabel("SOM_Note");
            this.lblDownload.Text = this.GetLabel("SOM_DownloadTheCQAContractorMaster",true);
            this.btnDownMTR.Text = this.GetLabel("SOM_DownloadDown");
        }

        private void ChangeLanguage_Click(object sender, System.EventArgs e)
        {
            SetLanguage();
        }
        
        #endregion

        #region Button or Link Click Event

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string fileName = "CQAQualificationMasterUpload_ERRORHighlight.xls";
            bool hasERROR = false;
            if (this.txtfileUpload.PostedFile.ContentLength <= 0)
            {
                this.Alert(this.GetMessage("SOM_FilePathNull"));
                return;
            }

            //Add by LiangZehong on 2008-12-18, for issue 0634 Begin...
            string fileType = string.Empty;
            fileType = this.txtfileUpload.PostedFile.FileName.Substring(this.txtfileUpload.PostedFile.FileName.LastIndexOf(".") + 1);
            if (fileType.ToLower() != ("xls").ToLower())
            {
                this.Alert(this.GetMessage("SOM_FileTypeError"));
                return;
            }
            //End...

            XmlDocument xdoc = new XmlDocument();
            string strDataValidation = "";
            try
            {
                xdoc.Load(this.txtfileUpload.PostedFile.InputStream);
                if (xdoc.GetElementsByTagName("Worksheet").Count > 1)
                {
                    Alert(GetMessage("SOM_OnesheetOnly"));
                    return;
                }
                string xpath = "ss:Workbook/ss:Worksheet/ss:Table/ss:Row[not (@ss:Hidden)]";
                System.Xml.XmlNamespaceManager xnm = new XmlNamespaceManager(xdoc.NameTable);

                xnm.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");

                XmlNodeList nodelist = xdoc.SelectNodes(xpath, xnm);
                int i = 0;
                XmlDocument xml = new XmlDocument();
                xml.LoadXml("<root/>");
                foreach (XmlNode node in nodelist)
                {
                    if (i > 0)// first row is head
                    {
                        string QualCode = "", QualDesc = "", FlagSOMAR = "", FlagObsolete = "";
                        try
                        {
                            for (int j = 0, k = 0; j < node.ChildNodes.Count; j++)
                            {
                                if (node.ChildNodes[j].Attributes["ss:Index"] != null)
                                {
                                    int h = 0;
                                    if (int.TryParse(node.ChildNodes[j].Attributes["ss:Index"].Value, out h))
                                    {
                                        k = h - 1;
                                    }
                                }
                                switch (k)
                                {
                                    case 0:
                                        if (node.ChildNodes[j] != null && node.ChildNodes[j].ChildNodes[0] != null) QualCode = node.ChildNodes[j].ChildNodes[0].InnerText.Trim();
                                        break;
                                    case 1:
                                        if (node.ChildNodes[j] != null && node.ChildNodes[j].ChildNodes[0] != null) QualDesc = node.ChildNodes[j].ChildNodes[0].InnerText.Trim();
                                        break;
                                    case 2:
                                        if (node.ChildNodes[j] != null && node.ChildNodes[j].ChildNodes[0] != null) FlagSOMAR = node.ChildNodes[j].ChildNodes[0].InnerText.Trim().ToUpper();
                                        break;
                                    case 3:
                                        if (node.ChildNodes[j] != null && node.ChildNodes[j].ChildNodes[0] != null) FlagObsolete = node.ChildNodes[j].ChildNodes[0].InnerText.Trim().ToUpper();
                                        break;
                                }
                                k++;
                            }
                            // data validation
                            if (QualCode == String.Empty && QualDesc == String.Empty && FlagSOMAR == String.Empty && FlagObsolete == String.Empty)
                            {
                                continue;
                            }

                            if ((QualCode == String.Empty) || (QualCode.Length > 20))
                            {
                                strDataValidation = string.Format(this.GetMessage("COM_ParameterLength"), this.GetLabel("SOM_QualificationCode"), "20");
                                throw new Exception();
                            }

                            if ((QualDesc == String.Empty) || (QualDesc.Length > 60))
                            {
                                strDataValidation = string.Format(this.GetMessage("COM_ParameterLength"), this.GetLabel("SOM_QualificationDesc"), "60");
                                throw new Exception();
                            }

                            if (FlagSOMAR != "Y" && FlagSOMAR != "N")
                            {
                                strDataValidation = this.GetLabel("SOM_FlagSOMAR") + GetMessage("SOM_ValueISYorN");
                                throw new Exception();
                            }
                            if (FlagObsolete != "Y" && FlagObsolete != "N")
                            {
                                strDataValidation = this.GetLabel("SOM_VoidYesOrNo") + GetMessage("SOM_ValueISYorN");
                                throw new Exception();
                            }
                        }
                        catch
                        {
                            i++;
                            hasERROR = true;
                            if (node.ChildNodes[0] != null) APJ.Util.Utility.AddAttribute(node.ChildNodes[0], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            if (node.ChildNodes[1] != null) APJ.Util.Utility.AddAttribute(node.ChildNodes[1], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            if (node.ChildNodes[2] != null) APJ.Util.Utility.AddAttribute(node.ChildNodes[2], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            if (node.ChildNodes[3] != null) APJ.Util.Utility.AddAttribute(node.ChildNodes[3], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");

                            ////APJ.Util.Utility.AddNode(node, "strDataValidation", "", strDataValidation);                            

                            continue;
                        }

                        XmlNode xnode = APJ.Util.Utility.AddNode(xml.FirstChild, "row", "");
                        APJ.Util.Utility.AddAttribute(xnode, "idx", i.ToString());
                        APJ.Util.Utility.AddNode(xnode, "QualCode", "", QualCode);
                        APJ.Util.Utility.AddNode(xnode, "QualDesc", "", QualDesc);
                        APJ.Util.Utility.AddNode(xnode, "FlagSOMAR", "", FlagSOMAR);
                        APJ.Util.Utility.AddNode(xnode, "FlagObsolete", "", FlagObsolete);
                    }
                    i++;
                }
                bool successful = true;
                DataTable dtReturn = new DataTable();
                //if (!hasERROR)  upload right data though include error data
                //{
                dtReturn = MTRC.ODMS.DAL.SOM.CodeSetup.CDQualMas.CQAQualificationMasterUpload(this.ODMUser.ID, this.ODMUser.ID, ref successful, xml);
                //}

                if (successful)
                {


                    if ((dtReturn.Rows.Count > 0) || (hasERROR))
                    {
                        string stylePath = "ss:Workbook/ss:Styles";
                        string stylePathS22 = "ss:Workbook/ss:Styles/ss:Style[@ss:ID='ODMS_ExportExcel']";
                        XmlNode nodeS22 = xdoc.SelectSingleNode(stylePathS22, xnm);
                        if (nodeS22 == null)
                        {//not exist style ODMS, create dynamically for highlight
                            XmlNode nodeStyles = xdoc.SelectSingleNode(stylePath, xnm);
                            XmlNode nodeStyle = APJ.Util.Utility.AddNode(nodeStyles, "Style", "urn:schemas-microsoft-com:office:spreadsheet", "");
                            APJ.Util.Utility.AddAttribute(nodeStyle, "ID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            XmlNode nodeInterior = APJ.Util.Utility.AddNode(nodeStyle, "Interior", "urn:schemas-microsoft-com:office:spreadsheet", "");
                            APJ.Util.Utility.AddAttribute(nodeInterior, "Color", "#FF0000", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            APJ.Util.Utility.AddAttribute(nodeInterior, "Pattern", "Solid", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                        }

                        foreach (DataRow row in dtReturn.Rows)
                        {
                            //---------------------huangyao----------
                            XmlNode node = nodelist.Item((int)row["idx"]);
                            for (int j = 0, k = 0; j < node.ChildNodes.Count; j++)
                            {
                                if (node.ChildNodes[j].Attributes["ss:Index"] != null)
                                {
                                    int h = 0;
                                    if (int.TryParse(node.ChildNodes[j].Attributes["ss:Index"].Value, out h))
                                    {
                                        k = h - 1;
                                    }
                                }

                                APJ.Util.Utility.AddAttribute(node.ChildNodes[j], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");

                                k++;
                            }
                            //--------------------------------------

                            //---------------------commentted by huangyao----------
                            //APJ.Util.Utility.AddAttribute(nodelist.Item((int)row["idx"]).ChildNodes[0], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            //APJ.Util.Utility.AddAttribute(nodelist.Item((int)row["idx"]).ChildNodes[1], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            //APJ.Util.Utility.AddAttribute(nodelist.Item((int)row["idx"]).ChildNodes[2], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            //APJ.Util.Utility.AddAttribute(nodelist.Item((int)row["idx"]).ChildNodes[3], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            //---------------end------commentted by huangyao----------
                        }
                        Response.Clear();
                        Response.Charset = "UTF-16";
                        Response.ContentEncoding = System.Text.Encoding.GetEncoding(1200);
                        Response.AddHeader("Content-disposition", "attachment;filename=" + fileName);
                        Response.ContentType = "application/vnd.ms-excel";
                        xdoc.Save(Response.OutputStream);
                        xdoc = null;
                        Response.End();

                    }
                    else
                    {
                        Alert(GetMessage("SOM_UpdateSuccessful"));
                    }
                }
                else
                {
                    xdoc = null;
                    Alert(GetMessage("SOM_UpdateError"));
                }
                xml = null;
            }
            catch (XmlException xmlException)
            {
                //Alert("Load file error. Please check the file format.");
                Alert(GetMessage("SOM_UploadFileFormatError"));
            }
            catch
            {
                Alert(GetMessage("SOM_UpdateError"));
            }
            finally
            {
                xdoc = null;
            }

        }


        protected void btnDownMTR_Click(object sender, EventArgs e)
        {
            DataSet ds = MTRC.ODMS.DAL.SOM.CodeSetup.CDQualMas.GetAllCDQualMas();
            DataTable dtSearchResult = ds.Tables[0];
            dtSearchResult.TableName = "CQA Qualification Master Upload";
            dtSearchResult.Columns.Remove("QualMasID");
            dtSearchResult.Columns.Remove("FlagSOMAR");
            dtSearchResult.Columns.Remove("FlagObsolete");
            dtSearchResult.Columns.Remove("LastUpdUser");
            dtSearchResult.Columns.Remove("LastUpdTime");
            dtSearchResult.Columns.Remove("ActingasUser");

            //----------------- Modify by zengshunbo 2008-12-11 actionlog(0709) ------------------

            //dtSearchResult.Columns[0].ColumnName = "Qualification Code";
            //dtSearchResult.Columns[1].ColumnName = "Qualification Description";
            //dtSearchResult.Columns[2].ColumnName = "For SOMS Admission Registry?(Y/N)";
            //dtSearchResult.Columns[3].ColumnName = "Valid?(Y/N)";

            dtSearchResult.Columns[0].ColumnName = this.GetLabel("SOM_QualificationCode", this.LangCode);
            dtSearchResult.Columns[1].ColumnName = this.GetLabel("SOM_QualificationDesc", this.LangCode);
            dtSearchResult.Columns[2].ColumnName = this.GetLabel("SOM_FlagSOMAR", this.LangCode);
            dtSearchResult.Columns[3].ColumnName = this.GetLabel("SOM_VoidYesOrNo", this.LangCode);

            //--------------- End modify by zengshunbo 2008-12-11 actionlog(0709) ------------------



            //Common.ExportExcel(ds, Context, "CQAQualificationMasterUpload.xls"); //-----huangyao 20090109: fixed action log item 0872
            Common.ExportExcel_showHHMM(ds, Context, "CQAQualificationMasterUpload.xls", "som_upload");  //-----huangyao 20090109: fixed action log item 0872
            dtSearchResult = null;
            ds = null;
        }

        protected void btnDownTemplte_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable("CQA Qualification Master Upload");

            //----------------- Modify by zengshunbo 2008-12-11 actionlog(0709) ------------------

            //dt.Columns.Add("Qualification Code");
            //dt.Columns.Add("Qualification Description");
            //dt.Columns.Add("For SOMS Admission Registry?(Y/N)");
            //dt.Columns.Add("Valid?(Y/N)");

            dt.Columns.Add(this.GetLabel("SOM_QualificationCode", this.LangCode));
            dt.Columns.Add(this.GetLabel("SOM_QualificationDesc", this.LangCode));
            dt.Columns.Add(this.GetLabel("SOM_FlagSOMAR", this.LangCode));
            dt.Columns.Add(this.GetLabel("SOM_VoidYesOrNo", this.LangCode));

            //--------------- End modify by zengshunbo 2008-12-11 actionlog(0709) ------------------

            ds.Tables.Add(dt);
            Common.ExportExcel(ds, Context, "CQAQualificationMasterUpload.xls");
        }
       
        #endregion



    }
}
